package main

import (
	"flag"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/config/file"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/registry"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
	"os"
	"shop-demo/app/shop/bff/internal/conf"
)

var (
	Name     = "shop-demo.user.service"
	Version  string
	confPath string
)

func init() {
	flag.StringVar(&confPath, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func main() {
	flag.Parse()
	logger := log.With(log.NewStdLogger(os.Stdout),
		"service.name", Name)
	bsConf, rConf := getConfig(confPath)
	tp := newTracerProvider(bsConf.Trace)

	app, cleanup, err := initApp(bsConf.Server, bsConf.Data, rConf, logger, tp)
	if err != nil {
		return
	}
	defer cleanup()

	if err := app.Run(); err != nil {
		panic(err)
	}

}

func getConfig(confPath string) (*conf.Bootstrap, *conf.Registry) {

	c := config.New(config.WithSource(file.NewSource(confPath)))

	if err := c.Load(); err != nil {
		panic(err)
	}

	var bsConf conf.Bootstrap

	if err := c.Scan(&bsConf); err != nil {
		panic(err)
	}

	var rConf conf.Registry

	if err := c.Scan(&rConf); err != nil {
		panic(err)
	}

	return &bsConf, &rConf
}

func newTracerProvider(c *conf.Trace) *trace.TracerProvider {

	exporter, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(c.Endpoint)))
	if err != nil {
		panic(err)
	}

	tracerProvider := trace.NewTracerProvider(
		trace.WithBatcher(exporter),
		trace.WithResource(resource.NewSchemaless(
			semconv.ServiceNameKey.String(Name),
		)),
	)

	return tracerProvider
}

func newApp(logger log.Logger, gs *grpc.Server, gh *http.Server, reg registry.Registrar) *kratos.App {
	app := kratos.New(
		kratos.Name(Name),
		kratos.Version(Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.Server(gs, gh),
		kratos.Registrar(reg),
	)
	return app
}
